const arr = [1, 2, 3, 4, 5];

function getAjax(url) {
    return new Promise(resolve => {
        console.log(url);
        // 模拟 Ajax 请求，这里使用 setTimeout 代替
        setTimeout(() => {
            resolve(url);
        }, Math.random() * 1000);
    });
}

class Solution {
    constructor(max) {
        this.queue = [];
        this.curCnt = 0;
        this.maxCnt = max;
        this.result = [];
    }

    add(url, index) {
        this.queue.push([url, index]);
        this.run();
    }

    run() {
        if (this.curCnt < this.maxCnt && this.queue.length !== 0) {
            let temp = this.queue.shift();
            let curURL = temp[0];
            let curIndex = temp[1];

            this.curCnt++;

            // Promise.resolve(getAjax(curURL)).then(res => {
            getAjax(curURL).then(res => {
                this.result[curIndex] = res;
                this.curCnt--;
                this.run();
            });
        } else if (this.queue.length === 0 && this.curCnt === 0) {
            // 当队列为空且当前请求数为0时，所有请求已完成，返回结果
            console.log("All requests completed.");
            console.log("Result:", this.result);
        }
    }
}

function fn(arr, max) {
    let sol = new Solution(max);

    for (let i = 0; i < arr.length; i++) {
        sol.add(arr[i], i);
    }
}

fn(arr, 3);